﻿using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Controls;
using System.Drawing;
using System.Collections;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Forms;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace WMP
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private int current_index;
        private bool lecture;
        private bool pause;
        private Playlists my_playlist = new Playlists();
        private Playlists my_biblio = new Playlists();
        private ConvertXML ConverteurXML = new ConvertXML();
        private DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        private bool nbuser = true;
        private string path_biblio = @"./biblio.xml";
        private bool justcreatedbiblio = false;
        private bool nextinbiblio = true;
        //public ObservableCollection<string> gridInfo { get; set; }

        public MainWindow()
        {
            timer.Tick += new EventHandler(dispatcherTimer_Tick);
            //timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
            timer.Interval = new TimeSpan(0, 0, 1);
            current_index = -1;
            lecture = false;
            pause = false;
            InitializeComponent();
            Slider_volume.Value = 100;
            Media.Volume = 1;
            if (!(File.Exists(path_biblio)))
            {
                File.Create(path_biblio);
                justcreatedbiblio = true;
            }
            if (!justcreatedbiblio)
                Loadbiblio();
            TheGrid.ItemsSource = my_biblio.getList();
        }

        private void Slider_volume_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Media.Volume = Slider_volume.Value / 100;
            Label_volume.Content = Convert.ToString(Convert.ToInt32(Slider_volume.Value));            
        }

        private void btn_play_Click(object sender, RoutedEventArgs e)
        {
            if (lecture)
            {
                btn_play.Content = "Play";
                lecture = false;
                pause = true;
                Media.Pause();
                timer.Stop();
            }
            else
            {
                lecture = true;
                btn_play.Content = "Pause";
                if (pause)
                {
                    pause = false;
                }
                else
                {
                    if (TheGrid.SelectedIndex != -1)
                    {
                        current_index = TheGrid.SelectedIndex;
                        Media.Source = new Uri("file:///" + my_biblio.liste[TheGrid.SelectedIndex].FilePath);
                    }
                    else if (playlist.SelectedIndex != -1) // Un item est selectionne
                    {
                        current_index = playlist.SelectedIndex;
                        Media.Source = new Uri("file:///" + my_playlist.liste[playlist.SelectedIndex].FilePath);
                        //System.Windows.Forms.MessageBox.Show(my_playlist.liste[playlist.SelectedIndex].FilePath);
                    }
                    else
                    {
                        current_index = 0;
                        if (my_biblio.liste.Count != 0)
                        {
                            Media.Source = new Uri("file:///" + my_biblio.liste[0].FilePath);
                            TheGrid.Items.Refresh();
                            TheGrid.SelectedIndex = current_index;
                            nextinbiblio = true;
                        }
                        else if (my_playlist.liste.Count != 0) // Il y a des items donc je vais lire le premier.
                        {
                            Media.Source = new Uri("file:///" + my_playlist.liste[0].FilePath);
                            playlist.Items.Refresh();
                            playlist.SelectedIndex = current_index;
                            nextinbiblio = false;
                        }
                    }
                }
                if (my_playlist.liste.Count != 0)
                {
                    //System.Windows.Forms.MessageBox.Show(Media.Clock.ToString());
                    //System.Windows.Forms.MessageBox.Show(my_playlist.liste[playlist.SelectedIndex].FilePath);
                    Media.Play();
                    timer.Start();
                }
            }
        }

        private void btn_plus_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Select a file";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                my_playlist.Add(dialog.FileName);
                playlist.Items.Add(my_playlist.liste[(my_playlist.liste.Count - 1)].FileName);
                playlist.Items.Refresh();
            }
        }

        private void btn_moins_Click(object sender, RoutedEventArgs e)
        {
            if (playlist.SelectedIndex != -1)
            {
                int index = playlist.SelectedIndex;
                my_playlist.Remove(playlist.SelectedIndex);
                playlist.Items.RemoveAt(playlist.SelectedIndex);
                playlist.Items.Refresh();
                if (playlist.SelectedIndex != 0)
                    playlist.SelectedIndex = index;
            }
        }

        private void btn_stop_Click(object sender, RoutedEventArgs e)
        {
            Media.Stop();
            btn_play.Content = "Play";
            lecture = false;
            pause = false;
            //Media.Source = null;
            timer.Stop();
            Slider_position.Value = 0;
            int tmp = Media.NaturalDuration.ToString().LastIndexOf('.');
            string length = Media.NaturalDuration.ToString();
            if (tmp > 0)
                length = length.Remove(tmp, length.Length - tmp);
            media_duration.Text = Media.Position.Hours + ":" + Media.Position.Minutes + ":" + Media.Position.Seconds + " / " + length;
        }

        private void btn_next_Click(object sender, RoutedEventArgs e)
        {
            if (!nextinbiblio)
            {
                if (my_playlist.liste.Count == 0)
                    nextinbiblio = true;
                if (current_index == (my_playlist.liste.Count - 1))
                    current_index = 0;
                else
                    current_index++;
                Media.Stop();
                if (my_playlist.liste.Count > 0)
                {
                    if (current_index > (my_playlist.liste.Count - 1))
                        current_index = 0;
                    Media.Source = new Uri("file://" + my_playlist.liste[current_index].FilePath);
                    playlist.Items.Refresh();
                    playlist.SelectedIndex = current_index;
                    Media.Play();
                }
            }
            if (nextinbiblio)
            {
                if (current_index == (my_biblio.liste.Count - 1))
                    current_index = 0;
                else
                    current_index++;
                Media.Stop();
                if (my_biblio.liste.Count > 0)
                {
                    if (current_index > (my_biblio.liste.Count - 1))
                        current_index = 0;
                    Media.Source = new Uri("file://" + my_biblio.liste[current_index].FilePath);
                    TheGrid.Items.Refresh();
                    TheGrid.SelectedIndex = current_index;
                    Media.Play();
                }
            }
        }

        private void btn_back_Click(object sender, RoutedEventArgs e)
        {
            if (!nextinbiblio)
            {
                if (my_playlist.liste.Count == 0)
                    nextinbiblio = true;
                if (current_index == 0)
                    current_index = (my_playlist.liste.Count - 1);
                else
                    current_index--;
                Media.Stop();
                if (my_playlist.liste.Count > 0)
                {
                    if (current_index > (my_playlist.liste.Count - 1))
                        current_index = 0;
                    Media.Source = new Uri("file://" + my_playlist.liste[current_index].FilePath);
                    playlist.Items.Refresh();
                    playlist.SelectedIndex = current_index;
                    Media.Play();
                }
            }
            if (nextinbiblio)
            {
                if (current_index == 0)
                    current_index = (my_biblio.liste.Count - 1);
                else
                    current_index--;
                Media.Stop();
                if (my_biblio.liste.Count > 0)
                {
                    if (current_index > (my_biblio.liste.Count - 1))
                        current_index = 0;
                    Media.Source = new Uri("file://" + my_biblio.liste[current_index].FilePath);
                    TheGrid.Items.Refresh();
                    TheGrid.SelectedIndex = current_index;
                    Media.Play();
                }
            }
        }

        private void btn_save_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxButtons buttons1 = MessageBoxButtons.OK;
            DialogResult result1;
            if (String.IsNullOrEmpty(Box_name_playlist.Text))
            {
                string message = "Remplissez correctement le champs : Nom";
                string caption = "Impossible de trouver le nom de la playlist";
                result1 = System.Windows.Forms.MessageBox.Show(message, caption, buttons1);
            }
            else
            {
                Box_name_playlist.Text.Trim();
                string message = "Enregistrer cette playlist : " + Box_name_playlist.Text + "?";
                string caption = "Enregistrement de playlist";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result;

                result = System.Windows.Forms.MessageBox.Show(message, caption, buttons);
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    ConverteurXML.ListToXml(my_playlist.liste, Box_name_playlist.Text);
                }
                string message2 = "Playlist enregistree";
                string caption2 = "OK";
                System.Windows.Forms.MessageBox.Show(message2, caption2, buttons1);
                Box_name_playlist.Clear();
            }
        }

        private void btn_load_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog_load = new OpenFileDialog();
            dialog_load.Title = "Selectionnez une playlist";
            dialog_load.InitialDirectory = "./PlaylistsXML";
            if (dialog_load.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                my_playlist.liste.Clear();
                playlist.Items.Clear();
                my_playlist.liste = ConverteurXML.XmlToList(dialog_load.FileName); //mettre le path direct ...
                foreach (ObjListe i in my_playlist.liste)
                {
                    playlist.Items.Add(i.FileName);
                }
                playlist.Items.Refresh();
            }
        }

        private void playlist_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lecture)
                Media.Stop();
            if (playlist.SelectedIndex != -1)
            {
                nextinbiblio = false;
                current_index = playlist.SelectedIndex;
                Media.Source = new Uri("file://" + my_playlist.liste[playlist.SelectedIndex].FilePath);
                Media.Play();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            bouttons_biblio.Visibility = Visibility.Hidden;
            lecteur_playlist.Visibility = Visibility.Visible;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            lecteur_playlist.Visibility = Visibility.Hidden;
            bouttons_biblio.Visibility = Visibility.Visible;
        }

        private void Media_MediaOpened(object sender, RoutedEventArgs e)
        {
            Slider_position.Value = 0;
            try
            {
                media_duration.Text = Media.NaturalDuration.ToString().Remove(Media.NaturalDuration.ToString().LastIndexOf('.'), Media.NaturalDuration.ToString().Length - Media.NaturalDuration.ToString().LastIndexOf('.'));
                timer.Start();
            }
            catch { }
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (Media.NaturalDuration.HasTimeSpan)
            {
                media_duration.Text = Media.Position.Hours + ":" + Media.Position.Minutes + ":" + Media.Position.Seconds + " / " + Media.NaturalDuration.ToString().Remove(Media.NaturalDuration.ToString().LastIndexOf('.'), Media.NaturalDuration.ToString().Length - Media.NaturalDuration.ToString().LastIndexOf('.'));
                Slider_position.Value = Convert.ToInt32((Media.Position.TotalMilliseconds * 100) / Media.NaturalDuration.TimeSpan.TotalMilliseconds);
            }
            nbuser = true;
            //Convert.ToString(Convert.ToInt32(Slider_volume.Value));
            // Forcing the CommandManager to raise the RequerySuggested event
            //CommandManager.InvalidateRequerySuggested();
        }

        private void Media_MediaEnded(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            Slider_position.Value = 0;
        }

        private void Slider_position_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //int i = (int)((Slider_position.Value * Media.NaturalDuration.TimeSpan.TotalMilliseconds) / 100);
            //TimeSpan ts = new TimeSpan(0, 0, 0, 0, i);
            if (Media.NaturalDuration.HasTimeSpan && nbuser == false)
                Media.Position = TimeSpan.FromMilliseconds((Slider_position.Value * Media.NaturalDuration.TimeSpan.TotalMilliseconds) / 100);
            nbuser = false;
            //Media.Position = ts;
        }
       private void biblio_plus_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Title = "Select a file";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                my_biblio.Add(dialog.FileName);
                TheGrid.Items.Refresh();
                Savebiblio();
            }
        }

        private void biblio_moins_Click(object sender, RoutedEventArgs e)
        {
            if (TheGrid.SelectedIndex != (-1))
            {
                int index_biblio = TheGrid.SelectedIndex;
                my_biblio.Remove(TheGrid.SelectedIndex); // Faire attention aux index quand le sort est modifie !  /!\ Probleme ! (Index Hors limite champs vide)
                TheGrid.Items.Refresh();
                if (index_biblio != 0)
                    TheGrid.SelectedIndex = index_biblio;
                Savebiblio();
            }
        }

        public void Loadbiblio()
        {
            my_biblio.liste = ConverteurXML.XmlToBiblio();
            TheGrid.Items.Refresh();
        }

        public void Savebiblio()
        {
            ConverteurXML.BiblioToXml(my_biblio.liste);
        }

        private void TheGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (TheGrid.SelectedIndex != -1)
            {
                if (lecture)
                    Media.Stop();
                nextinbiblio = true;
                current_index = TheGrid.SelectedIndex;
                Media.Source = new Uri("file://" + my_biblio.liste[TheGrid.SelectedIndex].FilePath);
                Media.Play();
            }
        }
    }
}